<?php
class Server {
  public static function submit_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    if ($req->name == '') {
      echo 'Name is empty';
      return;
    }
    
    if (isset($req->__nofile) && $req->__nofile == 1) {
      if (file_exists($req->file)) {
        unlink($req->file);
      }
      unset($req->__nofile);
      $req->file = '';
    }
    
    if (isset($req->__file) && $req->__file != '') {
      if (file_exists($req->__file)) {
        rename($req->__file, str_replace(TMP_DIR, UPLOAD_DIR_PLGN . $inst->__folder, $req->__file));
        $req->file = str_replace(TMP_DIR, UPLOAD_DIR_PLGN . $inst->__folder, $req->__file);
      }
      unset($req->__file);
    }
    
    if (isset($req->id) && $req->id != 0) {
      $orm->update('pb_ecom_brand', $req);
    } else {
      $orm->add('pb_ecom_brand', $req);
      $req->id = $orm->last_id();
    }
    
    if (isset($req->__pg)) {
      $req->__objs = $orm->get('pb_ecom_brand', 't.name', 'ASC', $req->__pg, SIZE, NULL);
    }
    
    echo json_encode($req);
  }
  
  public static function get_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    $opts = new stdClass();
    $opts->cd = 't.id = :v1';
    $opts->cdv = array(':v1' => $req->id);
    $res = $orm->get('pb_ecom_brand', NULL, NULL, NULL, NULL, $opts)->d;
    
    echo json_encode($res);
  }
  
  public static function upload_icon($orm, $sys, $inst, $is_iframe) {
    if (isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['error'] == 0) {
      //获得上传文件信息
      $upload_file = $_FILES['Filedata'];
      //获取文件扩展名
      $file_info = pathinfo($upload_file['name']);
      $file_ext = (isset($file_info['extension'])) ? $file_info['extension'] : '';
      
      $updir = UPLOAD_DIR_PLGN . $inst->__folder;
      if (!file_exists($updir)) {
        Utils::create($updir);
      }
        
      //获取客户端参数
      $id = Utils::get_param('id', 0);
      $file = Utils::get_param('file', '');
      if (file_exists($file) && is_file($file)) {
        unlink($file);
      }
      
      //Add custom code here...
      $file_ext = strtolower((isset($file_info['extension'])) ? $file_info['extension'] : '');
      $res = new stdClass();
      $res->id = $id;
      $res->file = (($id == 0) ? TMP_DIR : $updir) . '/' . Utils::unique() . '.' . $file_ext;
      if (move_uploaded_file($upload_file['tmp_name'], $res->file)) {
        if ($id != 0) {
          $orm->update('pb_ecom_brand', $res);
        }
        echo json_encode($res);
      }
    }
  }
}
?>